﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace TRTCMain.Common
{
    public class MeetingConfig
    {
        public int MicroVolume = 100;

        public int SpeakerVolume = 100;

        public string MicroName = string.Empty;

        public string SpeakerName = string.Empty;

        public string CameraName = string.Empty;

        private XmlSerializer ser = new XmlSerializer(typeof(MeetingConfig));

        private static MeetingConfig config;
        private static object lockObj = new object();
        private string FILEPATH = string.Empty;

        public static MeetingConfig GetInstance() {
            if (config == null) {
                lock (lockObj) {
                    if (config == null) {
                        config = new MeetingConfig();                        
                        config.LoadConfig();
                    }
                }
            }

            return config;
        }

        public MeetingConfig() {
            if (!Directory.Exists(System.Environment.GetEnvironmentVariable("AppData") + "/onemeeting/"))
            {
                Directory.CreateDirectory(System.Environment.GetEnvironmentVariable("AppData") + "/onemeeting/");
            }
            FILEPATH = System.Environment.GetEnvironmentVariable("AppData") + "/onemeeting/meetingconfig.xml";
        }

        public void LoadConfig() {
            try
            {
                if (File.Exists(FILEPATH))
                {
                    FileStream fs = new FileStream(FILEPATH, FileMode.Open);
                    var con = (MeetingConfig)ser.Deserialize(fs);
                    if (con != null)
                    {
                        this.CameraName = con.CameraName;
                        this.MicroName = con.MicroName;
                        this.SpeakerName = con.SpeakerName;
                        this.MicroVolume = con.MicroVolume;
                        this.SpeakerVolume = con.SpeakerVolume;
                    }
                    fs.Close();
                }
            }
            catch (Exception ex) {
                //TODO
            }
        }

        public void SaveConfig() {
            try
            {
                FileStream fs = new FileStream(FILEPATH, FileMode.Create);
                TextWriter tw = new StreamWriter(fs);
                ser.Serialize(tw, this);
                tw.Close();
                fs.Close();
            }
            catch (Exception e)
            {
                //TODO;
            }
        }
    }


}
